from doctest import debug_src

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class SnippetList(APIView):
    def get(self, request, format=None):
        snippets = Snippet.objects.all()
        seri = SnippetSerializer(snippets, many=True)
        return Response(seri.data)

    def post(self,request, format=None):
        deseri = SnippetSerializer(data=request.data)
        if deseri.is_valid():
            deseri.save()
            return Response(deseri.data, status=status.HTTP_201_CREATED)
        return Response(deseri.errors, status=status.HTTP_400_BAD_REQUEST)

class SnippetDetail(APIView):
    def get_object(self, pk):
        try:
            return Snippet.objects.get(pk=pk)
        except Snippet.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        snippet= self.get_object(pk)
        seri = SnippetSerializer(snippet)
        return Response(seri.data)

    def put(self, request, pk, format=None):
        snippet = self.get_object(pk)
        deseri = SnippetSerializer(snippet, data=request.data)
        if deseri.is_valid():
            deseri.save()
            return Response(deseri.data)
        return Response(deseri.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, reuqest, pk, format=None):
        snippet = self.get_object(pk)
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

